package com.vgemv.jsutilitysdk.Request.JsRequestManager2;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.vgemv.jsutilitysdk.JsJsonManager.JsJsonManager;
import com.vgemv.jsutilitysdk.SharedPreference.JsSharedPreferencesManager;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;



import okhttp3.Cookie;
import okhttp3.HttpUrl;

public class JsCookieManager {
    private static final String LOG_TAG = "JsCookieManager";
    private static final String COOKIE_PREFS = "Cookies_Prefs";


    /**
     * cookie的存储,应该是一个3层的树,第一key是host,第二层是cookieName,第三层是value.
     */
    private final Map<String, ConcurrentMap<String, Cookie>> mCookies;
    private final SharedPreferences cookiePrefs;

    public JsCookieManager(Context context) {
        cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
        ConcurrentMap<String, Cookie> cmp=new ConcurrentHashMap<String, Cookie>();
        mCookies = new HashMap<String, ConcurrentMap<String, Cookie>>();
        restore();

    }

    public void restore() {
        //将持久化的cookies缓存到内存中 即map cookies
        Map<String, ?> prefsMap = cookiePrefs.getAll();
        for(String host : prefsMap.keySet()) {
            String json = (String)prefsMap.get(host);
            if(json.length() > 0) {
                Type type = new TypeToken<ConcurrentHashMap<String, Cookie>>(){}.getType();
                ConcurrentHashMap<String, Cookie> map = JsJsonManager.fromJson(json,type);
                mCookies.put(host,map);
            }
        }
    }

//
//    public void resotreToken2() {
//        Map<String, ?> prefsMap = cookiePrefs.getAll();
//        for (Map.Entry<String, ?> entry : prefsMap.entrySet()) {
//            String[] cookieNames = TextUtils.split((String) entry.getValue(), ",");
//            for (String name : cookieNames) {
//                String encodedCookie = cookiePrefs.getString(name, null);
//                if (encodedCookie != null) {
//                    Cookie decodedCookie = decodeCookie(encodedCookie);
//                    if (decodedCookie != null) {
//                        if (!mCookies.containsKey(entry.getKey())) {
//                            mCookies.put(entry.getKey(),
//                                    new ConcurrentHashMap<String, Cookie>());
//                        }
//                        mCookies.get(entry.getKey()).put(name, decodedCookie);
//                    }
//                }
//            }
//        }
//    }

    protected String getCookieToken(Cookie cookie) {
        return cookie.name() + "@" + cookie.domain();
    }



    public void addCookies(HttpUrl url,List<Cookie> cookies) {
        for(Cookie cookie : cookies) {
            addCookieInMemory(url,cookie);
        }
        saveCookiesToSpForOneHost(url);
    }

    /**
     * 保存url的一个cookie.
     * @param url
     * @param cookie
     */
    public void addCookie(HttpUrl url, Cookie cookie) {
        addCookieInMemory(url,cookie);
        saveCookiesToSpForOneHost(url);
    }

    public void addCookieInMemory(HttpUrl url,Cookie cookie) {
        String name = getCookieToken(cookie);
        //不知道是我的原因还是哪里不对，所以自己写了判断
        if (!isCookieExpired(cookie)) {
            if (!mCookies.containsKey(url.host())) {
                mCookies.put(url.host(), new ConcurrentHashMap<String, Cookie>());
            }
            mCookies.get(url.host()).put(name, cookie);
        } else {
            //过期则删除该cookie.
            if (mCookies.containsKey(url.host())) {
                mCookies.get(url.host()).remove(name);
            }
        }
    }

//    private void saveCookiesForOneHost(String host,Map cookies) {
//        //讲cookies持久化到本地
//        SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
//        prefsWriter.putString(url.host(), TextUtils.join(",", mCookies.get(url.host()).keySet()));
//        prefsWriter.putString(name, encodeCookie(new SerializableOkHttpCookies(cookie)));
//        prefsWriter.apply();
//    }
    private void saveCookiesToSpForOneHost(HttpUrl httpUrl) {
        //讲cookies持久化到本地
        String host = httpUrl.host();
        Map oneHostCookies = mCookies.get(host);
        if(oneHostCookies != null) {
            SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
            String cookiesJson = JsJsonManager.toJson(oneHostCookies,false);
            prefsWriter.putString(host, cookiesJson);
            prefsWriter.apply();
        }
    }



    /** 当前cookie是否过期 */
    private static boolean isCookieExpired(Cookie cookie) {
        return cookie.expiresAt() < System.currentTimeMillis();
    }


    /**
     * 获取一个url的host的所有cookie
     * @param url
     * @return
     */
    public List<Cookie> getCookies(HttpUrl url) {
        ArrayList<Cookie> ret = new ArrayList<Cookie>();
        if (mCookies.containsKey(url.host()))
            ret.addAll(mCookies.get(url.host()).values());
        return ret;
    }

    //移除全部
    public boolean removeAll() {
        SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
        prefsWriter.clear();
        prefsWriter.apply();
        mCookies.clear();
        return true;
    }
    //移除指定cookie
    public boolean remove(HttpUrl url, Cookie cookie) {
        String name = getCookieToken(cookie);

        if (mCookies.containsKey(url.host()) && mCookies.get(url.host()).containsKey(name)) {
            mCookies.get(url.host()).remove(name);

            SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
            if (cookiePrefs.contains(name)) {
                prefsWriter.remove(name);
            }
            prefsWriter.putString(url.host(), TextUtils.join(",", mCookies.
                    get(url.host()).keySet()));
            prefsWriter.apply();
            return true;
        } else {
            return false;
        }
    }
    //获取全部cookie
    public List<Cookie> getCookies() {
        ArrayList<Cookie> ret = new ArrayList<Cookie>();
        for (String key : mCookies.keySet())
            ret.addAll(mCookies.get(key).values());
        return ret;
    }

//    /**
//     * cookies 序列化成 string
//     *
//     * @param cookie 要序列化的cookie
//     * @return 序列化之后的string
//     */
//    protected String encodeCookie(SerializableOkHttpCookies cookie) {
//        if (cookie == null)
//            return null;
//        ByteArrayOutputStream os = new ByteArrayOutputStream();
//        try {
//            ObjectOutputStream outputStream = new ObjectOutputStream(os);
//            outputStream.writeObject(cookie);
//        } catch (IOException e) {
//            Log.d(LOG_TAG, "IOException in encodeCookie", e);
//            return null;
//        }
//
//        return byteArrayToHexString(os.toByteArray());
//    }
//
//    /**
//     * 将字符串反序列化成cookies
//     *
//     * @param cookieString cookies string
//     * @return cookie object
//     */
//    protected Cookie decodeCookie(String cookieString) {
//        byte[] bytes = hexStringToByteArray(cookieString);
//        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
//        Cookie cookie = null;
//        try {
//            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
//            cookie = ((SerializableOkHttpCookies) objectInputStream.readObject()).getCookies();
//        } catch (IOException e) {
//            Log.d(LOG_TAG, "IOException in decodeCookie", e);
//        } catch (ClassNotFoundException e) {
//            Log.d(LOG_TAG, "ClassNotFoundException in decodeCookie", e);
//        }
//        return cookie;
//    }

    /**
     * 二进制数组转十六进制字符串
     *
     * @param bytes byte array to be converted
     * @return string containing hex values
     */
    protected String byteArrayToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        for (byte element : bytes) {
            int v = element & 0xff;
            if (v < 16) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(v));
        }
        return sb.toString().toUpperCase(Locale.US);
    }

    /**
     * 十六进制字符串转二进制数组
     *
     * @param hexString string of hex-encoded values
     * @return decoded byte array
     */
    protected byte[] hexStringToByteArray(String hexString) {
        int len = hexString.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) +
                    Character.digit(hexString.charAt(i + 1), 16));
        }
        return data;
    }
}
